What is array.prototype.flat?
The array.prototype.flat package provides functionality to flatten arrays up to a specified depth. This is particularly useful for dealing with nested arrays, allowing developers to easily manipulate and access elements within deeply nested structures. The package offers a polyfill for the Array.prototype.flat method, which is part of the ECMAScript 2019 standard but may not be available in all environments.
What are array.prototype.flat's main functionalities?
Flattening arrays
This feature allows you to flatten nested arrays up to a specified depth. In the code sample, the array is flattened up to 2 levels deep, resulting in [1, 2, 3, [4], 5].
[1, [2, [3, [4]], 5]].flat(2)
Other packages similar to array.prototype.flat
lodash.flatten
Lodash's flatten method is similar to array.prototype.flat but only flattens one level deep by default. Lodash also offers `flattenDeep` for deep flattening and `flattenDepth` to specify the depth, providing more flexibility compared to array.prototype.flat.
ramda.flatten
Ramda's flatten function offers functionality similar to array.prototype.flat, but like Underscore, it does not allow specifying the depth. It's part of a larger functional programming library, making it a good choice if you're already using Ramda for other purposes.
array.prototype.flat
An ES2019 spec-compliant Array.prototype.flat
shim/polyfill/replacement that works as far down as ES3.
This package implements the es-shim API interface. It works in an ES3-supported environment and complies with the proposed spec.
Because Array.prototype.flat
depends on a receiver (the this
value), the main export takes the array to operate on as the first argument.
Getting started
npm install --save array.prototype.flat
Usage/Examples
var flat = require('array.prototype.flat');
var assert = require('assert');
var arr = [1, [2], [], 3, [[4]]];
assert.deepEqual(flat(arr, 1), [1, 2, 3, [4]]);
var flat = require('array.prototype.flat');
var assert = require('assert');
delete Array.prototype.flat;
var shimmedFlat = flat.shim();
assert.equal(shimmedFlat, flat.getPolyfill());
assert.deepEqual(arr.flat(), flat(arr));
var flat = require('array.prototype.flat');
var assert = require('assert');
var shimmedIncludes = flat.shim();
var mapper = function (x) { return [x, 1]; };
assert.equal(shimmedIncludes, Array.prototype.flat);
assert.deepEqual(arr.flat(mapper), flat(arr, mapper));
Tests
Simply clone the repo, npm install
, and run npm test